package com.bobo.controller.base;


import com.bobo.annotations.RequestBody;
import com.bobo.annotations.RequestMapping;
import com.bobo.annotations.RequestMethod;
import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * Created by anting on 16/10/24.
 */


public class BaseServlet extends HttpServlet {

    static Logger log = Logger.getLogger(BaseServlet.class);

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        mapping(request, response, "POST");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        mapping(request, response, "GET");
    }


    private void mapping(HttpServletRequest request, HttpServletResponse response, String type) throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");


        String[] path = request.getRequestURI().split("/");
        String pathMethod = "";


        String[] end = {".css", ".js", ".png", ".jpg", ".jpeg", ".bmp", ".gif", ".jsp"};


        pathMethod = path[path.length - 1];



        boolean isPublic = false;

        for(String s : end) {
            if(pathMethod.endsWith(s)) {
                isPublic = true;
                break;
            }

        }

        if(!isPublic) {

        //TODO 需要修改最后的链接   /admin/user/add      /user/add     /index     /login
        try {





            boolean isOver = false;

            Object result = "";

            // getDeclaredMethods  获取本类中所有的方法
            //getMethods  包括继承的方法


            for (Method m : this.getClass().getDeclaredMethods()) {

                if (m.isAnnotationPresent(RequestMapping.class)) {

                    RequestMapping requestMapping = m.getAnnotation(RequestMapping.class);

                    // 获取定义的 方法类型 get / post
                    RequestMethod[] requestMethod = requestMapping.method();


                        for (RequestMethod r : requestMethod) {
                        //  方法类型是否匹配                         判断 注解中value 是否存在 对应的链接地址
                        if (r.toString().equals(type) && Arrays.asList(requestMapping.value()).contains("/" + pathMethod)) {
                            isOver = true;
                            //获取这个方法的参数列表  ru:   public String del(HttpServletRequest request, HttpServletResponse response){  中的request和 response
                            Class<?>[] parameterTypes = m.getParameterTypes();

                            //invoke 时用到的参数
                            Object[] obj = new Object[parameterTypes.length];

                            for (int i = 0; i < parameterTypes.length; i++) {
//                            String parameterName = clz.getName();
//                            System.out.println("参数名称:" + parameterName);

                                Class clz = parameterTypes[i];
                                //TODO 需要修改为动态赋值


                                 if("javax.servlet.http.HttpServletRequest".equals(clz.getName())) {
                                     obj[i] = request;
                                 } else if ("javax.servlet.http.HttpServletResponse".equals(clz.getName())) {
                                    obj[i] = response;
                                } else  {

                                Object object = clz.newInstance();


                                    obj[i] = object;
                                 }

                            }
                            result = m.invoke(this, obj);

                            // 判断是否为异步请求 需要返回字符串
                            if (m.isAnnotationPresent(RequestBody.class)) {
                                PrintWriter out = response.getWriter();
                                    out.write(result.toString());
                            } else if (result.toString().startsWith("redirect:")) {
                                response.sendRedirect(result.toString().replace("redirect:", ""));
                            } else {
                                request.getRequestDispatcher("/" + result.toString() + ".jsp").forward(request, response);
                            }
                        }



                    }


                }


                //跳出循环
                if (isOver) {
                    break;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    }

}
